
//
//  NSDate+Extension.swift
//  Weibo
//
//  Created by mac on 16/5/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

extension NSDate {

    class func sinaDate(createAt :String) -> NSDate {
    
        let dateFormatter = NSDateFormatter()
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        let createAtDate = dateFormatter.dateFromString(createAt)!
        return createAtDate
    }
    
    var sinaDateString :String? {
    
        /*
        判断是否是今年
            判断是否是今天
                判断是否是1分钟以内
                    刚刚
                判断是否是1小时之前
                    xx分钟前
                其它
                    xx小时前
            判断是否是昨天
                昨天 09:02
            其它
                05-06 10:02
        不是今年
            2015-10-10 10:10
        
        */
        let dateFormatter = NSDateFormatter()
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        
        if isThisYear(self) {
            
            let calendar = NSCalendar.currentCalendar()
            if calendar.isDateInToday(self) {
                let timeIntVal = abs(self.timeIntervalSinceNow)
                if timeIntVal < 60 {
                    
                    return "刚刚"
                }else if timeIntVal < 3600 {
                    
                    return "\(Int(timeIntVal / 60))分钟前"
                }else {
                    
                    return "\(Int(timeIntVal / 3600))小时前"
                }
                
            }else if calendar.isDateInYesterday(self) {
                
                dateFormatter.dateFormat = "昨天 HH:mm"
            }else {
                
                dateFormatter.dateFormat = "MM-dd HH:mm"
            }
        }else {
            
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
            
        }
        
        return dateFormatter.stringFromDate(self)
    
}
private func isThisYear(creatAtDate :NSDate) -> Bool {
    
    let currentDate = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
    dateFormatter.dateFormat = "yyyy"
    
    let currentYear = dateFormatter.stringFromDate(currentDate)
    let creatAtYear = dateFormatter.stringFromDate(creatAtDate)
    
    return currentYear == creatAtYear
}

}
